//  ==========支付相关============
var wx = wx || {};
var sendCount = 0, tz;
// 配置微信
function configWechat(){
    LXMBase.removeItem('timestamp');
    LXMBase.removeItem('nonceStr');
    $.ajax({
        type: 'post',
        url: httpsvr + '/oauth/wx/getconfig.do?url=' + encodeURIComponent(window.location.href),
        success: function(res){
            if (!res) {return;}
            res = JSON.parse(res);
            if (res && res.var && res.var.signature && wx && wx.config) {
                LXMBase.setItem('timestamp', res.var.timestamp);
                LXMBase.setItem('nonceStr', res.var.nonceStr);
                wx.config({
                    appId: res.var.appId,
                    timestamp: res.var.timestamp,
                    nonceStr: res.var.nonceStr,
                    signature: res.var.signature,
                    jsApiList: [
                        'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage',
                        'onMenuShareQQ', 'onMenuShareWeibo',
                        'hideMenuItems', 'showMenuItems',
                        'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem',
                        'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd',
                        'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice',
                        'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage',
                        'downloadImage', 'getNetworkType', 'openLocation', 'getLocation',
                        'hideOptionMenu', 'showOptionMenu', 'closeWindow',
                        'scanQRCode', 'chooseWXPay', 'openProductSpecificView',
                        'addCard', 'chooseCard', 'openCard'
                    ]
                });
                LXMBase.data.wxconfig = true;
            }
        },
        complete: function(res, stat){
            if (stat != 'success') {
                setTimeout(function(){ configWechat() }, 1000);
            }
        }
    });
}
// @Function 检查第三方支付的回调
// 目前pay_status = PAYED的处理只有微信才会这样返回
// 其他的支付会直接跳转到结果页/或pay_cancel_url/或类似浏览器的history.back
// 所以这里PAYED的处理只是从缓存中拿biz_result_id做判断
// 如果其他支付需要用到url传参的方式，请保持微信的处理同时修改这里的逻辑
function checkPayCallback(){
    var urlParams = LXMBase.getAllUrlParams(),
        pay_status = urlParams.pay_status,
        id = urlParams.proreport_biz_result_id,
        biz_source = LXMBase.getItem('biz_source');
    if (isWeixin) {
        id = LXMBase.getItem('biz_result_id');
    }
    if (!id || !pay_status) {return;}
    if (pay_status == 'PAYED') {
        LXMBase.data.proreport_biz_result_id = id;
        // showLoading();
        sendCount = 0;
        timeoutGetOrderStatus();
        alertMsg('',{
            text: '是否已经完成支付',
            cancelTxt: '暂未完成',
            cancel: function(){
                sendCount = 0;
                timeoutGetOrderStatus();
            },
            submitTxt: '完成支付',
            submit: function(){
                showLoading();
                sendCount = 0;
                timeoutGetOrderStatus();
            }
        });
    } else if (pay_status == 'CANCEL' || pay_status == 'UNPAY') {
        // 缓存支付使用
        LXMBase.data.proreport_biz_result_id = id;
        // 用做阻止刷新反复弹窗
        var bizType = LXMBase.getItem('PAY_FLAG');
        if (!bizType) {return;}
        LXMBase.removeItem('PAY_FLAG');
        // 弹起挽留窗体
        // openPopupStay();
    }
}

// 生成报告
function getResult(id){
    if (!id) {return;}
    var param = {
        uid: '', tk: '',
        cancellation: -1,
        body: {
            proreport_biz_result_id : id,
            biz_user_name: '',
            biz_user_sex: '',
            biz_user_phone: '',
            biz_user_birth: '',
            biz_user_birth_location: '',
            biz_user_livedate: '',
            biz_user_live_location: '',
            biz_user_name2: '',
            biz_user_sex2: '',
            biz_user_phone2: '',
            biz_user_birth2: '',
            biz_user_birth_location2: '',
            biz_user_livedate2: '',
            biz_user_live_location2: ''
        }
    };
    $.ajax({
        type: 'post',
        url: httpsvr + '/proreport/genProreport.do',
        data: JSON.stringify(param),
        success: function(res){
            //LXMBase.lxmIsNullJSON(res);
            if (!res) {alertMsg('网络有些繁忙请稍后再试哦(GETR,' + res.code + ')'); return;}
            if (res.code == 'S_OK') {
                window.location.href = 'report.html?proreport_biz_result_id=' + encodeURIComponent(id);
            } else if (res.code == 'FA_EXIST') {
                // alertMsg('您的测试结果已经生成，如需修改信息请重新购买哦');
                window.location.href = 'report.html?proreport_biz_result_id=' + encodeURIComponent(id);                
            } else {
                alertMsg('网络有些繁忙请稍后再试哦(GETR2,' + res.code + ')');
            }
        },
        error: function(){
            alertMsg('网络有些繁忙请稍后再试哦(GETR3)');
        }
    });
}

// 调起支付
function doPay(pay_type, pay_link){
    if (!pay_link) {
        alertMsg('调起支付失败，页面刷新后重试');
        return;
    }
    hideLoading();
    if (pay_type == 'WXJSPAY') {
        var product = getPrice(LXMBase.data.biz_type);
        localStorage.setItem('pay_link', JSON.stringify(pay_link));
        window.location.href = '/wxpay/dopay.html?price=' + encodeURIComponent(product.price) + '&name=' + encodeURIComponent(product.name);
    } else if (pay_type == 'IAPPPAY' || pay_type == 'CCPAY') {
        window.location.href = pay_link;
    } else if (pay_type == 'MWEB') {
        window.location.href = pay_link.mweb_url[0];
    } else {
        // 其余都调起ALIPAY
        $('#alipayform').html(pay_link);
    }
}

// 支付订单
function payOrder(id, pay_type, pay_cancel_url){
    var uid = LXMBase.getItem('biz_user_id'),
        biz_source = LXMBase.getItem('biz_source'),
        biz_operator = LXMBase.getItem('biz_operator') || '',
        biz_type = 'Senior';
    LXMBase.data.biz_type = 'Senior';
    LXMBase.data.pay_type = pay_type;

    if (!uid) {
        alertMsg('您没有登录哦');
        return;
    }
    if (!biz_source) {
        alertMsg('您没有登录哦.');
        return;
    }
    if (isWeixin && pay_type == 'WXJSPAY') {
        // 这2个参数必须要检测，为空微信不能调起支付
        var tmpTs = LXMBase.getItem('timestamp'),
            tmpNonce = LXMBase.getItem('nonceStr');

        if (!tmpTs || !tmpNonce) {
            alertMsg('正在等待微信接入，请稍后再试.');
            return;
        }
        if (!LXMBase.data.wxconfig) {
            alertMsg('正在等待微信接入，请稍后再试');
            return;
        }
    }
    var param = {
        uid: '', tk: '', cancellation: -1,
        body: {
            proreport_biz_result_id: id,
            pay_type: pay_type,
            pay_return_url: websvr + '/sdkpack/sdktarot3/payment.html?biz_source=' + biz_source + '&biz_back=true&pay_status=PAYED',
            pay_cancel_url: pay_cancel_url,
            biz_type: 'Senior',
            pay_status: '', biz_status: '',
            timestamp: '', nonceStr: ''
        }
    };
    if (isWeixin) {
        param.body.timestamp = LXMBase.getItem('timestamp');
        param.body.nonceStr = LXMBase.getItem('nonceStr');
    }
    showLoading();
    // 这里缓存的PAY_FLAG用于页面跳转回来，保存对套餐的选择以及刷新之后不在弹窗
    // @hackcode biz_type = LXM是用来区分异常处理的
    LXMBase.setItem('PAY_FLAG', ((biz_type == '') ? 'LXM' : biz_type));
    console.log(JSON.stringify(param))
    $.ajax({
        type: 'post',
        url: httpsvr + '/proreport/payProreport.do',
        data: JSON.stringify(param),
        success: function(res){
            console.log(res)
            hideLoading();
            if (!res) {alertMsg('系统繁忙，请稍后再试.'); return;}
            var data = res.var;
            if (res.code == 'S_OK') {
                LXMBase.data.proreport_biz_result_id = data.proreport_biz_result_id;
                LXMBase.setItem('biz_result_id',data.proreport_biz_result_id);
                // setTimeout(function(){
                //     alertMsg('',{
                //        text: '是否已经完成支付',
                //        cancelTxt: '暂未完成',
                //        cancel: function(){
                //            sendCount = 0;
                //            timeoutGetOrderStatus();
                //        },
                //        submitTxt: '完成支付',
                //        submit: function(){
                //            sendCount = 0;
                //            timeoutGetOrderStatus();
                //        }
                //    });
                // }, 1000);
                // 调起支付
                doPay(LXMBase.data.pay_type, data.pay_link);
            }else if( res.code == 'FA_EXIST' || res.code == 'FA_PAYED_NOREPORT'){ //FA_PAYED_NOREPORT表示已支付但未填写信息生成报告
                window.location.href = 'report.html?proreport_biz_result_id=' + id + '&biz_source=' + biz_source;
            }else{
                alertMsg('网络繁忙请稍后再试(PAYP2_' + res.code + ')');
            }
        },
        error: function(){
            // console.log('系统繁忙，请稍后再试(PAYP)');
            // alertMsg('系统繁忙，请稍后再试(PAYP)');
        }
    });
}

// @Function 同步订单状态
function getOrderStatus(){
    var id = LXMBase.data.proreport_biz_result_id;
    if (!id) {
        return false;
    }
    var param = {
        uid: '', tk: '',
        body: {
            proreport_biz_result_id: id,
            biz_status: '',
            access_token: ''
        }
    };
    $.ajax({
        type: 'post',
        url: httpsvr + '/proreport/queryOrderPayStatus.do',
        data: JSON.stringify(param),
        success: function(res){
            if (res && res.var && res.var.pay_status == 'PAYED') {
                var biz_source = LXMBase.getItem('biz_source');
                window.location.replace('report.html?proreport_biz_result_id=' + id + '&biz_source=' + biz_source);
            } else {
                timeoutGetOrderStatus();
            }
        },
        error: function(){
            timeoutGetOrderStatus();
        },
        complete: function(){
            sendCount++;
        }
    });

}
// @Function 验证订单状态
function timeoutGetOrderStatus(){
    clearTimeout(tz);
    if (sendCount < 3) {
        tz = setTimeout(function(){
            getOrderStatus();
        }, 1600);
    } else {
        hideLoading();
    }
}
// ==========支付相关END============

// 根据优惠信息获得价格
function getPrice(biz_type){
    if (!LXMBase.data.priceInfo) {
        LXMBase.data.priceInfo = {};
        LXMBase.data.priceInfo.arr = [
            {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8},
            {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8},
            {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8}
        ];
    }
    var priceInfo = LXMBase.data.priceInfo.arr[1];
    if (biz_type == '') {
        priceInfo = LXMBase.data.priceInfo.arr[0];
    } else if (biz_type == 'SE2') {
        priceInfo = LXMBase.data.priceInfo.arr[2];
    }
    var type = LXMBase.data.priceInfo.type ? LXMBase.data.priceInfo.type : '';
    var value = LXMBase.data.priceInfo.value ? LXMBase.data.priceInfo.value : 1;
    if (type == 'discount') { //打折
        priceInfo.price = (priceInfo.price * value).toFixed(2);
    } else if (type == 'reduce') { //满减
        priceInfo.price = priceInfo.price - value;
    } else if (type == 'real') {
        priceInfo.price = value;
    }
    return priceInfo;
}

// 获取折扣信息
function getCoupon(){
    LXMBase.data.priceInfo = {};
    LXMBase.data.priceInfo.arr = [
        {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8},
        {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8},
        {name: '爱情先知，塔罗全预测', beforePrice: 68.8, price: 18.8}
    ];
    var biz_source = LXMBase.getItem('biz_source'),
        biz_operator = LXMBase.getItem('biz_operator');
    var param = {
        uid: '', tk: '',
        body: {
            infoType: 'coupon',
            bizId: biz_id_map[biz_source],
            biz_source: biz_source,
            biz_operator: biz_operator
        }
    };
    $.ajax({
        type: 'post',
        url: httpsvr + '/proreport/getExtInfo.do',
        data: JSON.stringify(param),
        success: function(res){
            if( res && res.code == 'S_OK' && res.var && res.var.coupon ){
                var data = res.var.coupon;
                var tmpType = data.type,
                    tmpValue = data.value,
                    tmpPrice = LXMBase.data.priceInfo.arr[1].price;

                LXMBase.data.priceInfo.value = tmpValue;
                LXMBase.data.priceInfo.type = tmpType;
                if (tmpType == 'discount') {
                    // 这个项目对打折做了一个特殊处理
                    // 因为优惠项目是用套餐来做，所以这里的打折不直接乘以折扣
                    // 应该直接用价格来展示
                    tmpPrice = data.envalue;
                    // tmpPrice = (tmpPrice * tmpValue).toFixed(1);
                } else if (tmpType == 'reduce') {//满减
                    tmpPrice = (tmpPrice - tmpValue).toFixed(1);
                } else if (tmpType == 'real') {
                    tmpPrice = tmpValue;
                }
                $('.price').text(tmpPrice);
            }
        }
    });
}
